#include "sqlink.h"
#include <stdlib.h>


//创建连表
sqlink craete(sqlink H)
{
	//创建连表
	H =(sqlink)malloc(sizeof(sqlist));
	if( H == NULL)
	{
		printf("链表创建失败");
		return NULL;		
	}
	
	//赋值
	H->date = 0;
	H->next = NULL;

	//返回
	return H;
}


//尾部插入
int tall_insert(sqlink H, date_t value)
{
	sqlink p;
	//判断H
	if(H == NULL)
	{
		printf("链为空");
		return -1;
	}

	//申请新节点
	sqlink q;
	q =(sqlink) malloc(sizeof(sqlist));
	//判断
	if(q == NULL)
	{
		printf("q节点申请失败");
		return -1;
	}
	q->date = value;
	q->next = NULL;

	//找到尾节点
	p = H;
	while(p->next != NULL)
	{
		p = p->next;
	}

	//更新
	p->next = q;
	return 0;

}


//把已有的遍历出来
int show(sqlink H)
{
	if(H == NULL)
	{
		printf("链为空");
		return -1;
	}
	sqlink p;
	p = H;
	while(p->next != NULL)
	{
		printf("%d\n", p->next->date);
		p = p->next;
	}
	puts("");
	return 0;
}


//获取位置看看是否合理
sqlink get(sqlink H, int pos)
{
	sqlink p;
	if(H == NULL)
	{
		printf("空表");
		return 0;
	}

	//判断合理的位置
	if(pos == -1)
	{
		return H;
	}
	if(pos < -1)
	{
		printf("位置无效");
		return 0;
	}
	
	p = H;
	int i = -1;
	while(i < pos)
	{
		p = p->next;
		if(p == NULL)
		{
			printf("位置无效");
			break;
		}
		i++;
	}
	return p;
}



//插入
int insert(sqlink H, date_t value, int pos)
{
	sqlink p;
	int j= 0;
	int i = 0;
	if(H == NULL)
	{
		printf("链表为空");
		return -1;
	}

	//位子是否合理
	p = get(H, pos -1);
	if(p == NULL)
	{
		printf("位置为无效");
		return -1;
	}


	//新节点
	sqlink q;
	q = (sqlink)malloc(sizeof(sqlist));
	if(q == NULL)
	{
		printf("节点申请失败\n");
		return -1;
	}
	q->date = value;
	q->next = NULL;
	
	//插入
	q->next = p->next;
	p->next = q;
	return 0;

}


//删除元素
int dele(sqlink H, int pos)
{
	sqlink p;
	if(H == NULL)
	{
		printf("表为空\n");
		return -1;
	}

	int i = 0;
	p = get(H, pos-1);
	if(p == NULL)
	{
		printf("位置无效\n");
		return -1;
	}
	//更新值
	p->next = p->next->next;

	return 0;

}


//释放
sqlink list_free(sqlink H)
{
	sqlink p;
	if(H == NULL)
	{
		return H;
	}

	p = H;

	printf("free:");
	while( H != NULL)
	{
		p = H;
		printf("%d",p->date);
		free(p);
		H = H->next;	
	}
	return NULL;
}


















